/*
 * @Author: yangrongxin
 * @Date: 2021-05-31 15:03:22
 * @LastEditors: yangrongxin
 * @LastEditTime: 2021-09-29 10:09:12
 */
import React, { useState, useEffect } from 'react';
import { PickerView, PickerViewColumn, View, Button } from '@tarojs/components';
import { AtFloatLayout } from 'taro-ui';
import styles from './index.module.less';

interface IPickerWapperProps {
  indexValue?: number; // 用于控制当前选中的选项
  rangeList: string[]; // 用于选择的列表
  onChange?: any; // 修改当前参数的事件
  isOpened: boolean; // 当前弹窗是否进行展示
  onClose: any; // 关闭当前弹窗的事件
  title?: string; // 当前展示的提示文字
  confirmText?: string; // 当前弹窗确认按钮的文字
  layoutClassName?: string; // 当前扩展的layout样式
  titleClassName?: string; // 当前扩展的title样式
  pickerBodyClassName?: string; // pickerbodyclass
  pickerContentClassName?: string; // pickercontentclass
  btnGroup?: any;
}

const PickerWapper = (props: IPickerWapperProps) => {
  const {
    indexValue = 0,
    isOpened = true,
    onClose,
    rangeList = [],
    title,
    onChange,
    confirmText,
    layoutClassName,
    titleClassName,
    pickerBodyClassName,
    pickerContentClassName,
    btnGroup,
  } = props;

  const [selectorChecked, setSelectorChecked] = useState<number[]>([indexValue]);

  const onChangeFn = (e: any) => setSelectorChecked(e.detail.value);

  useEffect(() => {
    setSelectorChecked([indexValue]);
  }, [rangeList]);

  return (
    <View catchMove>
      <AtFloatLayout className={`${styles.container} ${layoutClassName}`} isOpened={isOpened} onClose={onClose}>
        {title && <View className={titleClassName || styles.title}>{title}</View>}
        <PickerView
          indicatorClass={`${styles.indicatorClass} ${pickerBodyClassName}`}
          className={`${styles.pickerView} ${pickerContentClassName}`}
          value={selectorChecked}
          onChange={onChangeFn}
        >
          <PickerViewColumn>
            {rangeList.map((item: string) => {
              return <View key={Math.random()}>{item}</View>;
            })}
          </PickerViewColumn>
        </PickerView>
        {btnGroup ? (
          React.cloneElement(btnGroup, {
            selectorChecked,
          })
        ) : (
          <Button
            onClick={() => {
              // 默认为0 当前选择的时候默认选择第一个
              const valIndex = selectorChecked[0] || 0;
              const valString = rangeList[valIndex];
              onChange && onChange(valString, valIndex);
            }}
          >
            {confirmText || '确定'}
          </Button>
        )}
      </AtFloatLayout>
    </View>
  );
};

export default PickerWapper;
